import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
import { activeRoutes } from '@/router/index'
// 路由跳转进度条
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// 白名单列表
const whiteList = ['/login', '/404']
// 添加路由守卫
router.beforeEach(async(to, from, next) => {
  console.log(to, '去到哪里')
  console.log(from, '来自哪里')
  // const title = getPageTitle('to.meta.title')
  document.title = getPageTitle(to.meta.title)
  // 开启进度条 跳转页面钱显示
  NProgress.start()
  const token = store.state.user.token

  if (token) {
    // 已登录
    if (to.path === '/login') {
      console.log('你已登录了,直接去首页')
      next('/')
      NProgress.done() // 关闭进度条 next指定了跳转地址 不会通过router.afterEach
    } else {
      // 跳转页面前发送请求获取用户信息
      // await store.dispatch('user/getlist')

      if (!store.state.user.userinfo.userId) {
        const menus = await store.dispatch('user/getlist')
        console.log(activeRoutes)
        const permenus = activeRoutes.filter(item => {
          // console.log('bugbugbug', item)
          return menus.includes(item.children[0].name)
        })
        console.log(menus)
        permenus.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('menus/updatamutation', permenus)
        router.addRoutes(permenus)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 去白名单
      console.log('拥有白名单 可以放行')
      next()
    } else {
      console.log('没有白名单 请先登录')
      next('/login')
      NProgress.done() // 关闭进度条
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 关闭进度条 页面跳转后
})
